package com.lp.controller;

import com.lp.po.Student;
import com.lp.po.User;
import com.lp.service.StudentService;
import com.lp.service.UserService;
import com.lp.utils.MDUtils;
import com.lp.utils.RegistUtil;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class RegistController {
    @Resource
    private UserService userService;
    @Resource
    private StudentService studentService;

    RegistUtil registUtil=new RegistUtil();

    //运行Ajax进行提交
    @RequestMapping("/selectName")
    @ResponseBody
    public Map<String,Object> selectName(String username) throws Exception {
        Student num=studentService.selectName(username);
        Map<String,Object> mapUser=new HashMap<String,Object>();
        if(num==null){
            mapUser.put("type", "success");
            return mapUser;
        }else {
            mapUser.put("type", "error");
            return mapUser;

        }
    }

    //注册管理员
    @RequestMapping(value ="/doRegist",method = RequestMethod.POST)
    public ModelAndView addUser(User user, String password, String repassword,Student student) throws Exception{
        ModelAndView mv=new ModelAndView();
        if(password.equals(repassword)) {
            //添加到student表中
            studentService.inset(student);

            //加密后存入user表中
            ByteSource salt=registUtil.getSalt(user.getUsername());
            user.setPassword(MDUtils.getMD5Password(user.getPassword(),salt).toString());
            userService.addUser(user);

            mv.addObject("zcmsg","注册成功！");
            mv.setViewName("login");
            return mv;
        }else{
            mv.addObject("zcmsg","注册失败！");
            mv.setViewName("login");
            return mv;
        }
    }
}
